(function() {

    'use strict';

    // 地址需要修改！！！！！
    var shareSDK = {

        _info : {
            shareTitle     : '《天下HD》奇幻冒险 萌动亚洲',
            descContent    : '《天下HD》奇幻冒险 萌动亚洲',
            shareTimeTitle : '《天下HD》奇幻冒险 萌动亚洲',
            imgUrl         : __CDNPATH + '/data/share.jpg',
            lineLink       : window.location.href
        },

        _doneCbk: null,

        _doneShareFriend: function() {
            nie.config.stats.url.add('1/txhd_mdyz.html?click=share', '分享给好友');
            this._doneCbk && this._doneCbk();
        },

        _doneShareTimeline: function() {
            nie.config.stats.url.add('1/txhd_mdyz.html?click=share', '分享到朋友圈');
            this._doneCbk && this._doneCbk();
        },

        set: function(info) {

            var that = this;

            if (info) {
                info.shareTitle     && (this._info.shareTitle     = info.shareTitle    );
                info.descContent    && (this._info.descContent    = info.descContent   );
                info.shareTimeTitle && (this._info.shareTimeTitle = info.shareTimeTitle);
                info.imgUrl         && (this._info.imgUrl         = info.imgUrl        );
                info.doneCbk        && (this._doneCbk             = info.doneCbk       );
            }

            wx.ready(function() {
                wx.onMenuShareAppMessage({
                    title   : that._info.shareTitle,
                    desc    : that._info.descContent,
                    link    : that._info.lineLink,
                    imgUrl  : that._info.imgUrl,
                    success : function() {
                        that._doneShareFriend();
                    }
                });
                wx.onMenuShareTimeline({
                    title   : that._info.shareTimeTitle,
                    link    : that._info.lineLink,
                    imgUrl  : that._info.imgUrl,
                    success : function() {
                        that._doneShareTimeline();
                    }
                });
            });

            return this;
        },

        init: function() {

            var that = this;

            document.addEventListener('YixinJSBridgeReady', function() {
                YixinJSBridge.on('menu:share:appmessage', function() {
                    YixinJSBridge.invoke('sendAppMessage', {
                      img_width  : '300',
                      img_height : '300',
                      img_url    : that._info.imgUrl,
                      link       : that._info.lineLink,
                      desc       : that._info.descContent,
                      title      : that._info.shareTitle
                    }, function() {
                        that._doneShareFriend();
                    });
                });
                YixinJSBridge.on('menu:share:timeline', function() {
                    YixinJSBridge.invoke('shareTimeline', {
                      img_width  : '300',
                      img_height : '300',
                      img_url    : that._info.imgUrl,
                      link       : that._info.lineLink,
                      desc       : that._info.shareTimeTitle,
                      title      : that._info.shareTimeTitle
                    }, function() {
                        that._doneShareTimeline();
                    });
                });
            }, false);

            wx.config(wx_conf);

            this.set();

            return this;
        }
    };

    var imgLoader = {

        _srcs      : [],
        _onLoaded  : null,
        _onLoading : null,

        load: function() {

            var srcs      = this._srcs,
                l         = srcs.length,
                loadCount = 0,
                that      = this,
                tmp,
                i;

            function onImgLoad() {
                if (++loadCount === l) {
                    that._onLoaded && that._onLoaded();
                } else {
                    that._onLoading && that._onLoading(Math.floor(loadCount / l * 100));
                }
            }

            if (!l) {
                that._onLoaded && that._onLoaded();
                return this;
            }

            for (i = l; i--;) {
                tmp        = new Image();
                tmp.src    = srcs[i];
                tmp.onload = onImgLoad;
            }

            return this;
        },

        reset: function(arrSrcs, onLoaded, onLoading) {

            this._srcs      = arrSrcs.slice(0);
            this._onLoaded  = onLoaded;
            this._onLoading = onLoading;

            return this;
        }
    };

    var audio = {

        _elTpl : '<div style="display:none;"><audio src="" preload autoplay loop></audio></div>',
        _elCtl : null,

        play: function() {
            this._elCtl.play();
            return this;
        },

        pause: function() {
            this._elCtl.pause();
            return this;
        },

        init: function(url) {

            var that = this;

            if (url) {
                this._elCtl = $(this._elTpl).find('audio').attr('src', url)[0];

                $(function() {
                    that._elCtl.play();
                });

                $('body').one('touchstart', function() {
                    that._elCtl.play();
                    return false;
                });
            }

            return this;
        }
    };

    var socket = {

        _HOST : 'http://s.webcgi.163.com:4944/shuangping',
        // _HOST : 'http://10.242.138.118:8348/shuangping',
        _sock : null,
        _msgCallbacks : [],

        stopListening: function() {
            this._msgCallbacks = [];
            return this;
        },

        listen: function(onMessage) {
            onMessage && this._msgCallbacks.push(onMessage);
            return this;
        },

        send: function(cmd, data) {
            this._sock.send(cmd + '+++' + data);
            return this;
        },

        init: function(callback) {

            var that = this;

            this._sock = new SockJS(this._HOST);

            this._sock.onopen = function() {
                setTimeout(function() {
                    callback && callback();
                }, 1000);
            };

            this._sock.onmessage = function(resp) {
                for (var i = that._msgCallbacks.length; i--;) {
                    that._msgCallbacks[i](resp.data);
                }
            };

            return this;
        }
    };

    var eventPool = {

        _pool: {},

        trigger: function(event, data) {

            var name, item;

            if (this._pool[event]) {
                for (name in this._pool[event]) {
                    item = this._pool[event][name];
                    item.cbk.call(item.ctx, data);
                }
            }
        },

        off: function(event, id) {

            if (this._pool[event]) {

                if (id) {
                    delete this._pool[event][id];
                } else {
                    delete this._pool[event];
                }
            }
        },

        on: function(event, callback, context) {

            var id = genRandId();

            function genRandId() {
                return new Date().getTime().toString() +
                        Math.floor(Math.random() * 10240);
            }

            this._pool[event] || (this._pool[event] = {});

            this._pool[event][id] = {
                cbk : callback,
                ctx : context
            };

            return id;
        },

        one: function(event, callback, context) {

            var id = this.on(event, function(data) {
                callback.call(context, data);
                this.off(event, id);
            }, this);

            return id;
        }
    };

    var utils = {

        getQueryString: function(name) {

            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'),
                r   = window.location.search.substr(1).match(reg);

            return (r != null) ? unescape(r[2]) : null;
        },

        moveItem: function(el, targetPos, speed, callback) {

            if (speed) {
                el.attr('style', '-webkit-transform:translateX(-' + targetPos +
                        'px);-webkit-transition:all ' + speed / 1000 + 's linear;');
                setTimeout(function() {
                    callback && callback();
                }, speed);

            } else {
                el.attr('style', '-webkit-transform:translateX(-' + targetPos + 'px);');
                callback && callback();
            }

            return this;
        },

        hideItem: function(el, speed, callback) {

            var style = el.attr('style');

            style = style ? style : '';

            el.attr('style', style + ';opacity:0;-webkit-transition:all ' +
                    speed / 1000 + 's;');

            setTimeout(function() {
                el.attr('style', style + ';display:none;');
                callback && callback();
            }, speed);

            return this;
        },

        showItem: function(el, speed, callback) {

            var style = el.attr('style');

            style = style ? style : '';

            el.attr('style', style + ';display:block;opacity:0;');

            setTimeout(function() {
                el.attr('style', style + ';display:block;opacity:1;' +
                        '-webkit-transition:all ' + (speed - 100) / 1000 + 's;');
            }, 100);

            setTimeout(function() {
                el.attr('style', style + ';display:block;');
                callback && callback();
            }, speed);

            return this;
        }
    };

    var coverCloud = {

        show: function() {
            $('.cover-cloud').removeClass('show');
            setTimeout(function() {
                $('.cover-cloud').addClass('show');
            }, 100);
            return this;
        }
    };

    var camera = {

        zoomIn: function($el, scale, pctx, pcty, speed) {
            $el.attr('style',
                    (speed ? '-webkit-transition:all ' + speed + 's;' : '') +
                    '-webkit-transform:scale(' + scale + ',' + scale + ');' +
                    '-webkit-transform-origin:' + pctx + '% ' + pcty + '%;');
            return this;
        },

        zoomBack: function($el, speed) {
            $el.attr('style',
                    (speed ? '-webkit-transition:all ' + speed + 's;' : '') +
                    '-webkit-transform:scale(1,1);');
            return this;
        }
    };

    var starArea = {

        hide: function() {
            $('.star-area').addClass('hidden');
            return this;
        },

        show: function() {
            $('.star-area').removeClass('hidden');
            return this;
        },

        showStar: function(name) {
            $('.star-area .star-' + name).addClass('active');
            return this;
        },

        init: function() {

            eventPool.one('OP_DONE_W1', function() {
                this.showStar('hanguo');
            }, this);

            eventPool.one('OP_DONE_W2', function() {
                this.showStar('taiwan');
            }, this);

            eventPool.one('OP_DONE_W3', function() {
                this.showStar('zhongguo');
            }, this);

            return this;
        }
    };

    var girl = {

        reset: function() {
            $('.girl .girl-stand').addClass('shown');
            $('.girl').attr('style', '')
                    .removeClass('fly-out fly-center').addClass('fly-in');
            return this;
        },

        showSleep: function() {
            utils.showItem($('.girl .girl-sleep'), 500);
            return this;
        },

        wakeup: function() {
            $('.girl .girl-sleep').remove();
            $('.girl .girl-wakeup').addClass('shown');
            setTimeout(function() {
                $('.girl .girl-wakeup').remove();
                $('.girl .girl-stand').addClass('shown');
            }, 2000);
            return this;
        },

        flyIn: function(speed) {
            setTimeout(function() {
                $('.girl').attr('style', '-webkit-transition:all ' +
                        (speed / 1000 - 0.1) + 's;').addClass('fly-center');
            }, 100);
            return this;
        },

        flyOut: function(speed) {
            setTimeout(function() {
                $('.girl').attr('style', '-webkit-transition:all ' +
                        (speed / 1000 - 0.1) + 's;').addClass('fly-out');
            }, 100);
            return this;
        },

        change: function() {
            utils.hideItem($('.girl .girl-stand'), 500, function() {
                $('.girl .girl-stand').remove();
            });
            utils.showItem($('.girl .girl-qilin'), 500);
            return this;
        }
    };

    var opWindow = {

        _currName : null,

        hide: function() {
            utils.hideItem($('.op-pop-shadow, .op-pop, .op-pop .' + this._currName), 1000);
            return this;
        },

        show: function(name) {
            this._currName = name;
            utils.showItem($('.op-pop-shadow, .op-pop, .op-pop .' + name), 1000);
            return this;
        },

        init: function() {

            eventPool.one('SEA_ARRIVE_HANGUO', function() {
                if ($('.op-pop .window1').length) {
                    this.show('window1');
                }
            }, this);

            eventPool.one('SEA_ARRIVE_TAIWAN', function() {
                this.show('window2');
            }, this);

            eventPool.one('SEA_ARRIVE_ZHONGGUO', function() {
                this.show('window3');
            }, this);

            return this;
        }
    };

    var opWindow1 = {

        init: function() {

            var el = $('.op-pop .window1');

            el.find('.op-window .btn-sel').click(function() {
                el.find('.op-window .btn-sel').removeClass('active');
                $(this).addClass('active');
                return false;
            });

            el.find('.op-window .btn-submit').click(function() {

                var selEl = el.find('.active');

                if (selEl.length) {

                    if (+selEl.data('target') === 1) {
                        el.find('.op-window').hide();
                        el.find('.tip-success').show();

                        eventPool.trigger('OP_DONE_W1');

                        setTimeout(function() {
                            opWindow.hide();
                        }, 3000);

                    } else {
                        el.find('.op-window').hide();
                        el.find('.tip-failed').show();
                    }
                }

                return false;
            });

            el.find('.tip-failed').bind('touchstart', function() {
                $(this).hide();
                el.find('.op-window').show();
                return false;
            });

            return this;
        }
    };

    var opWindow2 = {

        _el : $('.op-pop .window2'),

        _selfResult   : null,
        _friendResult : null,

        _judge: function() {

            var that = this;

            if (this._selfResult && this._friendResult) {
                if (this._selfResult === this._friendResult) {
                    this.setDone();
                } else {
                    setTimeout(function() {
                        that.reset();
                    }, 1500);
                }
            }

            return this;
        },

        showOpWindow: function() {
            this._el.find('.tip').hide();
            this._el.find('.op-window').show();
            return this;
        },

        reset: function() {
            this._el.find('.op-window .btn').removeClass('disabled');
            this._el.find('.op-window .remain').removeClass('active');
            this._selfResult = null;
            this._friendResult = null;
            return this;
        },

        setDone: function() {

            var that = this;

            this._el.find('.op-window .icon' + this._selfResult).removeClass('remain');
            this.reset();

            if (!this._el.find('.op-window .remain').length) {

                setTimeout(function() {
                    that._el.find('.op-window').hide();
                    that._el.find('.tip-success').show();

                    eventPool.trigger('OP_DONE_W2');

                    setTimeout(function() {
                        opWindow.hide();
                    }, 3000);
                }, 2000);
            }

            return this;
        },

        init: function() {

            var that = this;

            this._el.find('.tip .btn').click(function() {
                that._el.find('.tip').hide();
                that._el.find('.op-window').show();
                return false;
            });

            this._el.find('.op-window .btn').click(function() {

                var currEl = $(this),
                    result = currEl.data('target');

                if (!currEl.hasClass('disabled') && currEl.hasClass('remain')
                        && !currEl.hasClass('acitve')) {

                    that._selfResult = +result;

                    that._el.find('.op-window .remain').removeClass('active')
                            .addClass('disabled');

                    currEl.addClass('active').removeClass('disabled');

                    eventPool.trigger('OP_W2_SELECT', result);

                    that._judge();
                }

                return false;
            });

            eventPool.on('CMD_W2_SELECT', function(result) {
                this._friendResult = +result;
                this._judge();
            }, this);

            return this;
        }
    };

    var opWindow3 = {

        init: function() {

            var el = $('.op-pop .window3 .op-window'),
                currTarget = 1;

            el.find('.btn').click(function() {

                var currEl = $(this);

                if (+currEl.data('target') === currTarget) {
                    currEl.addClass('active');
                    ++currTarget;

                    if (currTarget > 4) {

                        setTimeout(function() {
                            eventPool.trigger('OP_DONE_W3');
                            opWindow.hide();
                        }, 1000);
                    }
                }

                return false;
            });

            return this;
        }
    };

    var endPage = {

        init: function() {

            $('.page-end .get-verify').click(function() {

                var phone = $('.page-end .phone').val(),
                    name  = $('.page-end .name').val();

                if (!name) {
                    alert('请输入您的姓名');

                } else if (!/^1[34578]\d{9}$/.test(phone)) {
                    alert('请输入正确的手机号码');

                } else {
                    $.ajax({
                        url : 'http://mobile-game-appoint.webapp.163.com/' +
                                'appoint/h2-apnt/' + phone + '/other/',
                        dataType      : 'jsonp',
                        scriptCharset : 'utf-8',
                        data : { extra : name },

                        success: function(resp) {
                            if (resp.status === 'ok') {
                                alert('验证码已成功发送到手机，请注意查收');
                            } else {
                                alert(resp.status);
                            }
                        },

                        error: function() {
                            alert('网络错误，请刷新重试');
                        }
                    });
                }

                return false;
            });

            $('.page-end .submit').click(function() {

                var phone  = $('.page-end .phone').val(),
                    verify = $('.page-end .verify').val();

                if (!/^1[34578]\d{9}$/.test(phone)) {
                    alert('请输入正确的手机号码');

                } else if (!verify) {
                    alert('请输入验证码');

                } else {
                    $.ajax({
                        url: 'http://mobile-game-appoint.webapp.163.com/' +
                                'appoint_submit_authcode/h2-apnt/' + phone + '/other/',
                        dataType      : 'jsonp',
                        scriptCharset : 'utf-8',
                        data : { auth_code : verify },

                        success: function(resp) {
                            if (resp.status === 'ok') {
                                $('.page-share').fadeIn(1000);
                            } else {
                                alert(resp.status);
                            }
                        },

                        error: function() {
                            alert('网络错误，请刷新重试');
                        }

                    });
                }

                return false;
            });

            return this;
        }
    };

    starArea.init();

    opWindow.init();
    opWindow1.init();
    opWindow2.init();
    opWindow3.init();

    endPage.init();

    $('.wrapper, .cover-cloud').bind('touchmove', function() {
        return false;
    });

    window.commonJs = {
        shareSDK   : shareSDK,
        imgLoader  : imgLoader,
        audio      : audio,
        socket     : socket,
        eventPool  : eventPool,
        utils      : utils,
        coverCloud : coverCloud,
        camera     : camera,
        starArea   : starArea,
        girl       : girl
    }

}());
